package com.cskaoyan.market.aspect;

import com.cskaoyan.market.db.domain.MarketFootprint;
import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.service.wx.WxFootPrintService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Author: chenjian
 * @Date: 2024/5/21 19:53
 */
@Component
@Aspect
public class FootPrintAspect {
    @Autowired
    SecurityManager securityManager;
    @Autowired
    WxFootPrintService wxFootPrintService;

    @Pointcut("@annotation(com.cskaoyan.market.annotation.FootprintAdd)")
    public void pt1() {
    }

    @After("pt1()")
    public void addFootPrint(JoinPoint joinPoint) {

        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");

        Object[] args = joinPoint.getArgs();
        try {
            Integer goodsId = (Integer) args[0];
            int userId = user.getId();
            LocalDateTime addTime = LocalDateTime.now();
            LocalDateTime updateTime = LocalDateTime.now();
            MarketFootprint marketFootprint = wxFootPrintService.addFootprint(userId, goodsId, addTime, updateTime);
            if(marketFootprint!=null){
                System.out.println("足迹添加成功");
            }else{
                System.out.println("足迹添加失败");
            }
        } catch (NumberFormatException e) {
            System.out.println("参数类型不匹配");
        }
    }
}
